let express = require("express");

let Router = express.Router(); //获取Router对象用于开启路由 Router==app，比app对象多了路由管理功能
let mongo = require("../../db/mongo"); //mongo
let upload = require("./multer"); //上传文件
let config = require("../../config.json"); //端口号和路径

//上传多个商品图片

//新增商品
Router.post("/addgoods", upload.array("photos", 5), async (req, res) => {
  // console.log(req.files); //存图片
  // console.log(req.body); //其他部分数据
  let arr = req.files; //[{}]
  let goodinf = {};
  let img = [];
  arr.forEach((item) => {
    // console.log(item, 999);
    let imginf = {};
    let str = item.path.replace(/\\/, "/"); // uploads/xxx.jpg
    let url = config.URL + str;
    imginf.url = url; //图片路径
    imginf.title = item.filename; //图片名
    img.push(imginf);
  });

  // console.log(img, 888);
  goodinf = {
    img,
    ...req.body, //扩展运算符的使用
  };

  //存到数据库里面
  let data = {};
  try {
    let newarr = [];
    newarr.push(goodinf);
    let p = await mongo.insert({
      colname: "good",
      data: newarr,
    });
    if (p.flag) {
      //不为零:注册成功
      data = {
        code: 2000,
        flag: true,
        message: "注册成功",
      };
    } else {
      //注册失败
      data = {
        code: 3000,
        flag: false,
        message: "注册失败",
      };
    }
  } catch (err) {
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }

  // console.log(goodinf, 666);

  res.send(data);
});

// let good = {
//   name : '',
//   price,
//   size:,
//   color:,
//   img : [
//     {
//       title : '图片1',
//       url : 'xxx'
//     },{
//       title : '图片2',
//       url : 'xxx'
//     },{
//       title : '图片3',
//       url : 'xxx'
//     }
//   ]
// }

module.exports = Router;
